import jwt
from datetime import datetime, timedelta
from rest_framework.response import Response

class Jwt:
  # 密钥，用于签名和验证JWT
  secret_key = 'wt_app'
  algorithm = 'HS256'

  # 生成token
  @classmethod
  def encode(self, payload, exp_time = datetime.utcnow() + timedelta(hours = 5)):
    """
      生成token

      :return 返回生成的token
    """
    # 判断载荷是否存在，不存在直接返回空串
    if not payload:
      return ''

    payload['exp'] = exp_time
    # 生成 token
    token = jwt.encode(
      payload,
      self.secret_key,
      algorithm=self.algorithm,
    )

    return token

  @classmethod
  def verifty_token(self, token):
    try:
      payload = jwt.decode(token, self.secret_key, algorithms=[self.algorithm])
      return {
        'code': 200,
        'data': payload,
        'message': 'token success'
      }
    except jwt.ExpiredSignatureError:
      
      # token 过期
      return {
        'code': 400,
        'data': None,
        'message': 'Token 过期'
      }
    except jwt.InvalidTokenError:
      # token 无效
      return {
        'code': 400,
        'data': None,
        'message': 'Token 无效'
      }



def verifty_token():
  def outwrapper(func):
    def wrapper(*args, **kwargs):
      class_name, request = args
      token = request.headers.get('Authorization')

      # 'Bearar aaa.bbb.ccc'
      token = token.split(' ')[1]
      res = Jwt.verifty_token(token)
      if res['code'] == 200 :
        kwargs['payload'] = res['data']
        return func(*args, **kwargs)
      else:
        return Response(res)
    return wrapper
  return outwrapper